package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {

    private static String[] notcheckUris = new String[]{
            "/backend/**",
            "/front/**",
            "/common/**",
            "/employee/login",
            "/employee/logout",
            "/user/sendMsg",
            "/user/login","/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1、获取本次请求的URI
        String requestURI = req.getRequestURI();
        log.info("请求的uri为: {}", requestURI);

        //2、判断本次请求是否需要处理
        boolean check = check(requestURI);

        //3、如果不需要处理，则直接放行
        if(!check){
            log.info("该路径 {} 不需要校验" , requestURI);
            chain.doFilter(req,resp);//放行
            return;
        }

        //4、判断登录状态，如果已登录，则直接放行 -----> 后台
        if(req.getSession().getAttribute("employee") != null){
            log.info("该用户已经登录, 执行放行");

            //System.out.println("当前线程ID: " + Thread.currentThread().getId());

            //获取当前登录用户ID, 存入ThreadLocal
            Long currentId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(currentId);

            chain.doFilter(req,resp);//放行

            //删除ThreadLocal中的数据
            BaseContext.removeCurrentId();

            return;
        }


        //4、判断登录状态，如果已登录，则直接放行 -----> 移动端
        if(req.getSession().getAttribute("user") != null){
            log.info("该用户已经登录, 执行放行");
            //获取当前登录用户ID, 存入ThreadLocal
            Long currentId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(currentId);
            chain.doFilter(req,resp);//放行
            //删除ThreadLocal中的数据
            BaseContext.removeCurrentId();
            return;
        }


        //5、如果未登录则 , 返回未登录结果
        R result = R.error("NOTLOGIN");
        resp.getWriter().write(JSON.toJSONString(result));
        return;
    }


    /**
     *
     * @param requestURI
     * @return  false : 不需要校验, true: 校验
     */
    private boolean check(String requestURI) {
        //循环数组, 匹配数组中每一个路径
        for (String uri : notcheckUris) {
            if(PATH_MATCHER.match(uri, requestURI)){
                return false;
            }
        }
        return true;
    }
}
